package cn.jhz.learn.community_dynamic.security.service;


import cn.jhz.learn.community_dynamic.security.helper.LoginHelper;
import cn.jhz.learn.community_dynamic.security.manager.JwtManager;
import cn.jhz.learn.community_dynamic.security.manager.SecurityUserManager;
import cn.jhz.learn.community_dynamic.security.model.SimpleGrantedUser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


@Service
public class JsonUserDetailsService implements UserDetailsService {

    private final SecurityUserManager<?> userManager;
    private final JwtManager jwtManager;

    @Autowired
    public JsonUserDetailsService(@Lazy @Qualifier("userManager") SecurityUserManager<?> userManager, JwtManager jwtManager) {
	super();
	this.userManager = userManager;
	this.jwtManager = jwtManager;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
	Object temp;
        switch (LoginHelper.getAccountType()) {
        	case EMAIL:
        	    temp = userManager.getUserDetailByEmail(username).orElseThrow(()->new UsernameNotFoundException("账号不存在!"));
        	    LoginHelper.setLoginUser(temp);
        	    return userManager.adpt((SimpleGrantedUser) temp);
        	case PHONE:
        	    temp = userManager.getUserDetailByPhone(username).orElseThrow(()->new UsernameNotFoundException("账号不存在!"));
        	    LoginHelper.setLoginUser(temp);
        	    return userManager.adpt((SimpleGrantedUser) temp);
        	case USERNAME:
        	    temp = userManager.getUserDetailByUsername(username).orElseThrow(()->new UsernameNotFoundException("账号不存在!"));
        	    LoginHelper.setLoginUser(temp);
        	    return userManager.adpt((SimpleGrantedUser) temp);
        	case JWT:
        	case LOGIN_ID:
        	    temp = userManager.getUserDetailByLoginId(username).orElseThrow(()->new UsernameNotFoundException("账号不存在!"));
        	    LoginHelper.setLoginUser(temp);
        	    return userManager.adpt((SimpleGrantedUser) temp);
        	case OPEN_ID:
          	  //TODO OpenID
        	default:
        	    throw new UsernameNotFoundException("账号格式错误!");
	}
    }
    
    public void register(String phone) {
        this.userManager.createUserByPhone(phone);
    }
    
    public void deleteLoginInfo(String username){
        jwtManager.clearRsaJsonWebKey(username);
    }
}
